package com.hdu.h_health.model;

import android.app.ProgressDialog;
import android.content.Context;
import android.text.TextUtils;

import com.hdu.h_health.bean.User;
import com.hdu.h_health.event.UpdateEvent;
import com.hdu.h_health.model.i.QueryUserListener;
import com.hdu.h_health.model.i.UpdateCacheListener;
import com.hdu.h_health.utils.CommonUtils;
import com.orhanobut.logger.Logger;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.greenrobot.event.EventBus;

/**
 * 用户相关操作类
 * Created by 612 on 2016/3/8.
 */
public class UserModel extends BaseModel {

    private static UserModel instanceUserModel = new UserModel();

    public static UserModel getInstance() {
        return instanceUserModel;
    }

    //检查用户是否登录
    public boolean checkIsLogin(Context context){
        BmobUser user=BmobUser.getCurrentUser(context,User.class);
        if (user==null){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 用户登录
     */
    public void login(Context context, String username, String password, final LogInListener listener) {
        if (TextUtils.isEmpty(username)) {
            listener.internalDone(new BmobException(CODE_NULL, "请填写账号"));
            return;
        }
        if (!isEmailNo(username) && !isMoblieNo(username)) {
            listener.internalDone(new BmobException(CODE_NOT_EQUAL, "邮箱/手机号格式不正确"));
            return;
        }
        if (TextUtils.isEmpty(password)) {
            listener.internalDone(new BmobException(CODE_NULL, "请填写密码"));
            return;
        }
        final ProgressDialog progress = new ProgressDialog(context);
        progress.setMessage("正在登陆...");
        progress.setCanceledOnTouchOutside(false);
        progress.show();
        final User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.login(getContext(), new SaveListener() {
            @Override
            public void onSuccess() {
                listener.done(getCurrentUser(), null);
                progress.dismiss();
            }

            @Override
            public void onFailure(int i, String s) {
                listener.done(user, new BmobException(i, s));
                progress.dismiss();
            }
        });
    }

    /**
     * 退出登录
     */
    public void logout() {
        BmobUser.logOut(getContext());
    }

    /**
     * 用户注册
     */
    public void register(Context context, String username, String password, String pwdagain, final LogInListener listener) {
        if (TextUtils.isEmpty(username)) {//判断账号是否为空
            listener.internalDone(new BmobException(CODE_NULL, "请填写邮箱/手机号"));
            return;
        }
        if (!isEmailNo(username) && !isMoblieNo(username)) {//判断账号格式是否正确
            listener.internalDone(new BmobException(CODE_NOT_EQUAL, "邮箱/手机号格式不正确"));
            return;
        }
        if (TextUtils.isEmpty(password)) {//判断密码是否为空
            listener.internalDone(new BmobException(CODE_NULL, "请填写密码"));
            return;
        }
        if (TextUtils.isEmpty(pwdagain)) {//判断密码是否为空
            listener.internalDone(new BmobException(CODE_NULL, "请确认密码"));
            return;
        }
        if (!password.equals(pwdagain)) {//判断前后密码是否一致
            listener.internalDone(new BmobException(CODE_NOT_EQUAL, "两次输入的密码不一致，请重新输入"));
            return;
        }
        final ProgressDialog progress = new ProgressDialog(context);
        progress.setMessage("正在注册...");
        progress.setCanceledOnTouchOutside(false);
        progress.show();
        final User user = new User();
        //设置用户账号为手机或邮箱
        user.setUsername(username);
        //设置用户手机号或邮箱
        if (isMoblieNo(username)) user.setMobilePhoneNumber(username);
        if (isEmailNo(username)) user.setEmail(username);
        //设置密码
        user.setPassword(password);
        user.setAvatar(" ");
        user.setSex(true);//设置默认性别
        user.setNick(" ");
        user.setSummary(" ");
        user.setCity(" ");
        user.setAge(0);
        user.setCollege("");
        user.setJob("");
        user.setOrganization("");
        user.setProvince("");
        user.setStudentNumber(0);
        user.setTeacherNumber(0);
        user.setType(0);
        user.setUniversity("");
        user.signUp(getContext(), new SaveListener() {
            @Override
            public void onSuccess() {
                listener.done(null, null);
                progress.dismiss();
            }

            @Override
            public void onFailure(int i, String s) {
                listener.done(null, new BmobException(i, s));
                progress.dismiss();
            }
        });
    }

    /**
     * 查询用户
     */
    public void queryUsers(String username, int limit, final FindListener<User> listener) {
        BmobQuery<User> query = new BmobQuery<>();
        //去掉当前用户
        try {
            BmobUser user = BmobUser.getCurrentUser(getContext());
            query.addWhereNotEqualTo("username", user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        query.addWhereContains("username", username);
        query.setLimit(limit);
        query.order("-createdAt");
        query.findObjects(getContext(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                if (list != null && list.size() > 0) {
                    listener.onSuccess(list);
                } else {
                    listener.onError(CODE_NULL, "查无此人");
                }
            }

            @Override
            public void onError(int i, String s) {
                listener.onError(i, s);
            }
        });
    }

    private int LIMIT=10;
    /**
     * 根据用户类型来查找用户
     */
    public void queryUserByType(Context context,int type, int page, FindListener<User> findListener) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("type", type);//查询不同类型的用户
        query.setLimit(LIMIT);
        query.setSkip(LIMIT*page);
        query.order("-createdAt");
        query.findObjects(context,findListener);
    }

    /**
     * 查询用户信息
     */
    public void queryUserInfo(String objectId, final QueryUserListener listener) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("objectId", objectId);
        query.findObjects(getContext(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                if (list != null && list.size() > 0) {
                    listener.internalDone(list.get(0), null);
                } else {
                    listener.internalDone(new BmobException(000, "查无此人"));
                }
            }

            @Override
            public void onError(int i, String s) {
                listener.internalDone(new BmobException(i, s));
            }
        });
    }

    /**
     * 更新用户资料和会话资料
     */
    public void updateUserInfo(MessageEvent event, final UpdateCacheListener listener) {
        final BmobIMConversation conversation = event.getConversation();
        final BmobIMUserInfo info = event.getFromUserInfo();
        String username = info.getName();
        String title = conversation.getConversationTitle();
        Logger.i("" + username + "," + title);
        //sdk内部，将新会话的会话标题用objectId表示，因此需要比对用户名和会话标题--单聊，后续会根据会话类型进行判断
        if (!username.equals(title)) {
            UserModel.getInstance().queryUserInfo(info.getUserId(), new QueryUserListener() {
                @Override
                public void done(User s, BmobException e) {
                    if (e == null) {
                        String name = s.getUsername();
                        String avatar = s.getAvatar();
                        Logger.i("query success：" + name + "," + avatar);
                        conversation.setConversationIcon(avatar);
                        conversation.setConversationTitle(name);
                        info.setName(name);
                        info.setAvatar(avatar);
                        //更新用户资料
                        BmobIM.getInstance().updateUserInfo(info);
                        //更新会话资料
                        BmobIM.getInstance().updateConversation(conversation);
                    } else {
                        Logger.e(e);
                    }
                    listener.done(null);
                }
            });
        } else {
            listener.done(null);
        }
    }

    /**
     * 更新个人信息
     */
    public void updateMyInfo(final int type, final Context context, User updateUser) {
        BmobUser bmobUser = getCurrentUser();
        updateUser.update(context, bmobUser.getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                EventBus.getDefault().post(new UpdateEvent(type,"更新成功"));
            }

            @Override
            public void onFailure(int i, String s) {
                EventBus.getDefault().post(new UpdateEvent(type,"更新失败!"));
                CommonUtils.showLog(i+s);
            }
        });
    }

    //判断手机号是否正确
    private boolean isMoblieNo(String mobile) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    //判断邮箱是否合法
    private boolean isEmailNo(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }
}
